package com.yc.sole.erp.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.common.enums.CommonState;
import com.yc.sole.erp.dto.CustomerDto;
import com.yc.sole.erp.entity.Customer;
import com.yc.sole.erp.exception.ErpResultEnum;
import com.yc.sole.erp.mapper.CustomerMapper;
import com.yc.sole.erp.request.CustomerQueryReq;
import com.yc.sole.framework.exception.BaseException;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 客户表 服务接口实现
 *
 * @author yizuomin
 * @date 2023-05-07
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerRepository extends ServiceImpl<CustomerMapper, Customer> {

    /**
     * 新增客户表
     *
     * @param customerDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCustomer(CustomerDto customerDto) {
        Customer entity = new Customer();
        BeanUtil.copyProperties(customerDto, entity);
        this.save(entity);
    }

    /**
     * 通过Id修改客户表
     *
     * @param customerDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomerById(CustomerDto customerDto) {
        Customer entity = new Customer();
        BeanUtil.copyProperties(customerDto, entity);
        this.updateById(entity);
    }

    /**
     * 修改客户应收款
     *
     * @param customerId
     * @param amount
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateReceivables(Long customerId, BigDecimal amount) {
        Customer customer = this.getById(customerId);
        if (Objects.isNull(customer)) {
            throw new BaseException(ErpResultEnum.CUSTOMER_NOT_FOUND);
        }
        Customer updateCustomer = new Customer();
        updateCustomer.setId(customerId);
        BigDecimal receivables = customer.getReceivables() == null ? BigDecimal.ZERO : customer.getReceivables().add(amount);
        updateCustomer.setReceivables(receivables);
        this.updateById(updateCustomer);
    }

    /**
     * 通过id删除客户表
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomerByIds(Collection<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 根据id获取客户表
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public List<CustomerDto> selectCustomerByIds(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(this.listByIds(ids), CustomerDto.class);
    }

    /**
     * 根据id获取客户表
     *
     * @param id
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public CustomerDto selectCustomerById(Long id) {
        return BeanUtil.copyProperties(this.getById(id), CustomerDto.class);
    }

    /**
     * 分页查询客户表
     *
     * @param page
     * @return RestResult
     */
    public Paging<CustomerDto> selectCustomerPage(Paging page, CustomerQueryReq customerPageReq) {
        LambdaQueryWrapper<Customer> queryWrapper = Wrappers.<Customer>lambdaQuery()
                .like(CharSequenceUtil.isNotBlank(customerPageReq.getCustomerNo()), Customer::getCustomerNo, customerPageReq.getCustomerNo())
                .like(CharSequenceUtil.isNotBlank(customerPageReq.getCustomerName()), Customer::getCustomerName, customerPageReq.getCustomerName())
                .like(CharSequenceUtil.isNotBlank(customerPageReq.getPhoneNum()), Customer::getPhoneNum, customerPageReq.getPhoneNum())
                .eq(Objects.nonNull(customerPageReq.getState()), Customer::getState, customerPageReq.getState())
                .orderByDesc(Customer::getId);
        return PageUtil.pageCopy(this.page(PageUtil.toMybatisPage(page), queryWrapper), CustomerDto.class);
    }

    /**
     * 查询客户列表
     *
     * @return RestResult
     */
    public List<CustomerDto> selectCustomerByName(String customerName) {
        LambdaQueryWrapper<Customer> queryWrapper = Wrappers.<Customer>lambdaQuery()
                .like(CharSequenceUtil.isNotBlank(customerName), Customer::getCustomerName, customerName)
                .eq(Customer::getState, CommonState.ENABLE)
                .orderByDesc(Customer::getId);
        Page<Customer> customerPage = new Page<>(1, 10);
        return BeanUtil.copyToList(this.page(customerPage, queryWrapper).getRecords(), CustomerDto.class);
    }

    /**
     * 查询所有客户
     *
     * @param queryReq
     * @return
     */
    public List<CustomerDto> selectAllCustomer(CustomerQueryReq queryReq) {
        LambdaQueryWrapper<Customer> wrapper = Wrappers.<Customer>lambdaQuery().and(CharSequenceUtil.isNotBlank(queryReq.getKeyword()),
                        w -> w.like(Customer::getCustomerName, queryReq.getKeyword())
                                .or().like(Customer::getCustomerNo, queryReq.getKeyword()))
                .orderByAsc(Customer::getFirstLetter);
        return BeanUtil.copyToList(this.list(wrapper), CustomerDto.class);
    }
}
